package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.LookDetialsAdapter;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.LookDetails2Bean;
import com.wnhz.work.yz.bean.RadioBean;
import com.wnhz.work.yz.bean.ReservedOddBean;
import com.wnhz.work.yz.bean.YusuanOrderBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.NoScrollListView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ReservedDetailActivity extends BaseActivity implements View.OnClickListener {
    private NoScrollListView listView;
    private LookDetialsAdapter adapter;
    private TextView xiaoji, zonghe;
    private TextView xiaoshouyuan;
    private TextView projectName;
    private RecyclerView all_info;
    private TextView area;
    private TableRow select_radio;
    private TextView radio;
    private TextView init_price, finish_price;
    private TextView manager_price, shui_price, li_price, max_yusaun;
    private TextView other_price;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reserved_detail);
        upLoad();

    }

    private RadioBean radioBean = new RadioBean();

    private void upLoad() {
        Map<String, Object> map = new HashMap<>();
        showDialog();

        XUtil.Post(Url.BATH_CONFIGLINKBUDGET, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        radioBean = gson.fromJson(result, RadioBean.class);
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                handler.sendEmptyMessage(1);
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            initAll();
            super.handleMessage(msg);
        }
    };

    private void initAll() {
        getAllData();
        initTilte();
        initView();
        initData();
    }

    private String project_name;
    private List<ReservedOddBean.InfoEntity.DataEntity> data = new ArrayList<>();
    private String record_id;
    private double other_money, main_money, person_money;

    private void getAllData() {
        record_id = getIntent().getStringExtra("record_id");
        project_name = getIntent().getStringExtra("project_name");
        data = (List<ReservedOddBean.InfoEntity.DataEntity>) getIntent().getSerializableExtra("data");
        list.clear();
        for (int i = 0; i < data.size(); i++) {
            list.add(new LookDetails2Bean());
            other_money += Double.parseDouble(data.get(i).getOther_money());
            main_money += Double.parseDouble(data.get(i).getMain_money());
            person_money += Double.parseDouble(data.get(i).getPerson_money());
            upLoad(i);
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        otherPrice = (TextView) findViewById(R.id.otherPrice);
        otherPrice.setText("￥" + df.format(other_money));
        mainPrice = (TextView) findViewById(R.id.mainPrice);
        mainPrice.setText("￥" + df.format(main_money));
        personPrice = (TextView) findViewById(R.id.personPrice);
        personPrice.setText("￥" + df.format(person_money));
    }

    private LinearLayout ll_xiaoji, ll_zonghe;
    private TextView otherPrice, mainPrice, personPrice;

    private List<LookDetails2Bean> list = new ArrayList<>();

    private void upLoad(final int position) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("budget_package_id", data.get(position).getCart_id());
        showDialog();
        XUtil.Post(Url.BATH_SEEPACKAGEGOODSLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        LookDetails2Bean bean = gson.fromJson(result, LookDetails2Bean.class);
                        list.set(position, bean);
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });
    }

    private void initData() {
    }

    private void initView() {
        other_price = (TextView) findViewById(R.id.other_price);
        manager_price = (TextView) findViewById(R.id.manager_price);
        shui_price = (TextView) findViewById(R.id.shui_price);
        li_price = (TextView) findViewById(R.id.li_price);
        max_yusaun = (TextView) findViewById(R.id.max_yusuan);
        select_radio = (TableRow) findViewById(R.id.select_radio);
        select_radio.setOnClickListener(this);
        radio = (TextView) findViewById(R.id.radio);
        init_price = (TextView) findViewById(R.id.init_price);
        finish_price = (TextView) findViewById(R.id.finish_price);
        area = (TextView) findViewById(R.id.area);
        xiaoji = (TextView) findViewById(R.id.xiaoji);
        zonghe = (TextView) findViewById(R.id.zonghe);
        xiaoji.setOnClickListener(this);
        zonghe.setOnClickListener(this);
        listView = (NoScrollListView) findViewById(R.id.listView);
        xiaoshouyuan = (TextView) findViewById(R.id.xiaoshouyuan);
        xiaoshouyuan.setText(MyApplication.getInstance().getUserBean().getUserName() + "");
        projectName = (TextView) findViewById(R.id.project_name);
        projectName.setText(project_name + "");
        all_info = (RecyclerView) findViewById(R.id.all_info);
        all_info.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        xiaoji.setBackgroundResource(R.mipmap.left_blue);
        xiaoji.setTextColor(getResources().getColor(R.color.white));
        zonghe.setBackgroundResource(R.mipmap.right_white);
        zonghe.setTextColor(getResources().getColor(R.color.main_color));
        ll_xiaoji= (LinearLayout) findViewById(R.id.ll_xiaoji);
        ll_zonghe= (LinearLayout) findViewById(R.id.ll_zonghe);
        updatePrice();
        base = new BaseRVAdapter(this, data) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_sing_details;
            }

            @Override
            public void onBind(final BaseViewHolder viewHolder, final int position) {
                x.image().bind(viewHolder.getImageView(R.id.yulan), data.get(position).getCad_img());
                x.image().bind(viewHolder.getImageView(R.id.cad_img), data.get(position).getCad_img());

                //
                x.image().bind(viewHolder.getImageView(R.id.shop_img), data.get(position).getImg());
                viewHolder.setTextView(R.id.sku_name, data.get(position).getPackage_sku_info());
                viewHolder.setTextView(R.id.title, data.get(position).getPackage_name());
                viewHolder.setTextView(R.id.sku, data.get(position).getPackage_cate());
                viewHolder.setTextView(R.id.desc, data.get(position).getPackage_sku_info());
                viewHolder.setTextView(R.id.room_num, data.get(position).getRoom_number());
                DecimalFormat df = new DecimalFormat("######0.00");
                viewHolder.setTextView(R.id.price, "￥" +df.format (Double.parseDouble(data.get(position).getPackage_money()) * radiosNum));
                viewHolder.setTextView(R.id.shopping_number, "￥" + data.get(position).getNums());
                final ImageView is_select = viewHolder.getImageView(R.id.is_select);


                viewHolder.getTextView(R.id.shopping_number).setText("" + data.get(position).getNums());
                //
                viewHolder.getImageView(R.id.ll_add).setTag(viewHolder.getTextView(R.id.shopping_number));
                viewHolder.getImageView(R.id.ll_add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView textView = (TextView) v.getTag();
                        int nums = 1;
                        try {
                            nums = Integer.parseInt(textView.getText().toString()) + 1;
                        } catch (Exception w) {
                            nums = 1;
                        }
                        data.get(position).setNums(nums + "");
                        //
                        updatePrice();
                        textView.setText("" + nums);
                    }
                });
                viewHolder.getImageView(R.id.reduce).setTag(viewHolder.getTextView(R.id.shopping_number));
                viewHolder.getImageView(R.id.reduce).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView textView = (TextView) v.getTag();
                        int nums = 1;
                        try {
                            nums = Integer.parseInt(textView.getText().toString()) - 1;
                        } catch (Exception w) {
                            nums = 1;
                        }
                        if (nums == 0) {
                            MyToast("再减就没了");
                            nums = 1;
                        }

                        data.get(position).setNums(nums + "");
                        //
                        updatePrice();
                        textView.setText("" + nums);
                    }
                });
                viewHolder.getTextView(R.id.shopping_number).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(ReservedDetailActivity.this);
                        View view = View.inflate(ReservedDetailActivity.this, R.layout.dialog_edit, null);
                        TextView queding1 = (TextView) view.findViewById(R.id.queding1);
                        TextView quxaio1 = (TextView) view.findViewById(R.id.quxiao1);
                        final EditText shopping_number = (EditText) view.findViewById(R.id.shopping_number);
                        shopping_number.setText(data.get(position).getNums());
                        builder.setView(view);
                        final AlertDialog show = builder.show();
                        Window dialogWindow = show.getWindow();
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        dialogWindow.setGravity(Gravity.CENTER);
                        dialogWindow.setAttributes(lp);
                        queding1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                int nums = Integer.parseInt(data.get(position).getNums());
                                try {
                                    nums = Integer.parseInt(shopping_number.getText().toString());
                                } catch (Exception e) {
                                    nums = Integer.parseInt(data.get(position).getNums());
                                }
                                data.get(position).setNums(nums + "");
                                updatePrice();
                                viewHolder.getTextView(R.id.shopping_number).setText(nums + "");
                                show.dismiss();
                            }
                        });
                        quxaio1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                show.dismiss();
                            }
                        });

                    }
                });
                viewHolder.getView(R.id.max_ll).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ReservedDetailActivity.this, UpdateDetialsActivity.class);
                        intent.putExtra("bean", list.get(position));
                        intent.putExtra("position", position);
                        intent.putExtra("cardId", data.get(position).getCart_id());
                        startActivityForResult(intent, UPDANUM);
                    }
                });
            }


        };
        all_info.setAdapter(base);
    }

    private BaseRVAdapter base;
    private static final int UPDANUM = 4422;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case UPDANUM:
                if (resultCode == RESULT_OK) {
                    LookDetails2Bean bean = (LookDetails2Bean) data.getSerializableExtra("bean");
                    int positon = data.getIntExtra("position", 0);
                    this.list.set(positon, bean);
                    String total_price = data.getStringExtra("total_price");
                    this.data.get(positon).setPackage_money(total_price);
                    base.notifyDataSetChanged();
                    updatePrice();
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void updatePrice() {
        double total = 0;
        double areaNum = 0d;
        for (int i = 0; i < data.size(); i++) {
            total += Double.parseDouble(data.get(i).getPackage_money()) * Double.parseDouble(data.get(i).getNums()) * radiosNum;
            areaNum += Double.parseDouble(data.get(i).getArea()) * Double.parseDouble(data.get(i).getNums());
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        double a = Double.parseDouble(radioBean.getInfo().getOther_money());
        other_price.setText("￥" + a);
        double b = Double.parseDouble(df.format(total * Double.parseDouble(radioBean.getInfo().getManage_percent())));
        manager_price.setText("￥" + b);
        double c = Double.parseDouble(df.format(total * Double.parseDouble(radioBean.getInfo().getTax_percent())));
        shui_price.setText("￥" + c);
        double d = Double.parseDouble(df.format(total * Double.parseDouble(radioBean.getInfo().getFrofits_percent())));
        li_price.setText("￥" + d);

        init_price.setText("￥" + df.format(total + a + b + c + d));
        Log.e("aaa", "" + a + "---" + df.format(total * Double.parseDouble(radioBean.getInfo().getManage_percent())));
        finish_price.setText("￥" + df.format(Double.parseDouble(init_price.getText().toString().substring(1, init_price.getText().toString().length())) * Double.parseDouble(radio.getText().toString())));
        area.setText(areaNum + "㎡");
    }


    private void initTilte() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("预算详情");
        findViewById(R.id.submit).setOnClickListener(this);
        findViewById(R.id.submit).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView right = (TextView) findViewById(R.id.submit);
        right.setText("生成订单");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:
//                Intent intent2 = new Intent(this, CreatOrderActivity.class);
//                startActivity(intent2);
                creatOrder();
                break;
            case R.id.xiaoji:
                xiaoji.setBackgroundResource(R.mipmap.left_blue);
                xiaoji.setTextColor(getResources().getColor(R.color.white));
                zonghe.setBackgroundResource(R.mipmap.right_white);
                zonghe.setTextColor(getResources().getColor(R.color.main_color));
                ll_xiaoji.setVisibility(View.VISIBLE);
                ll_zonghe.setVisibility(View.GONE);
                break;
            case R.id.zonghe:
                xiaoji.setBackgroundResource(R.mipmap.left_white);
                xiaoji.setTextColor(getResources().getColor(R.color.main_color));
                ll_xiaoji.setVisibility(View.GONE);
                ll_zonghe.setVisibility(View.VISIBLE);
                zonghe.setBackgroundResource(R.mipmap.right_blue);
                zonghe.setTextColor(getResources().getColor(R.color.white));
                break;
            case R.id.select_radio:
                initCustomOptionPicker();
                break;
        }

    }

    private void creatOrder() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        StringBuffer sb = new StringBuffer("[");
        for (int i = 0; i < data.size(); i++) {
            sb.append("{\"cart_id\":\"" + data.get(i).getCart_id() + "\",");
//            sb.append("\"sku_id\":\"" + 828 + "\",");
            sb.append("\"nums\":\"" + data.get(i).getNums() + "\",");
            sb.append("\"package_money\":\"" + data.get(i).getPackage_money() + "\",");
            sb.append("\"data\":[");
            for (int j = 0; j < list.get(i).getInfo().size(); j++) {
                sb.append("{\"cate_id\":\"" + list.get(i).getInfo().get(j).getCate_id() + "\",");
                sb.append("\"data\":[");
                for (int k = 0; k < list.get(i).getInfo().get(j).getData().size(); k++) {
                    sb.append("{\"goods_id\":\"" + list.get(i).getInfo().get(j).getData().get(k).getGoods_id() + "\",");
                    sb.append("\"goods_nums\":\"" + list.get(i).getInfo().get(j).getData().get(k).getGoods_nums() + "\",");
                    sb.append("\"sku_id\":\"" + list.get(i).getInfo().get(j).getData().get(k).getSku_id() + "\",");
                    sb.append("\"goods_price\":\"" + list.get(i).getInfo().get(j).getData().get(k).getGoods_price() + "\"");
                    sb.append("}");
                    if (k != list.get(i).getInfo().get(j).getData().size() - 1) {
                        sb.append(",");
                    }
                }
                sb.append("]}");
                if (j != list.get(i).getInfo().size() - 1) {
                    sb.append(",");
                }
            }
            sb.append("]}");
            if (i != data.size() - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        map.put("json_str", sb.toString());
        //record_id（备案）、other_money（其它费用）、manage_money（管理费）、tax_money（税费）
        // 、frofits_money（利润）、sale_name（销售员）、area（面积）、first_price（预算价）
        // 、end_price（最终预算价）、coefficient（预算系数）
        map.put("record_id", record_id);
        map.put("other_money", other_price.getText().toString().substring(1, other_price.getText().toString().length()));
        map.put("manage_money", manager_price.getText().toString().substring(1, manager_price.getText().toString().length()));
        map.put("tax_money", shui_price.getText().toString().substring(1, shui_price.getText().toString().length()));
        map.put("frofits_money", li_price.getText().toString().substring(1, li_price.getText().toString().length()));
        map.put("sale_name", MyApplication.getInstance().getUserBean().getUserName());
        map.put("area", area.getText().toString());
        map.put("first_price", init_price.getText().toString().substring(1, init_price.getText().toString().length()));
        map.put("end_price", finish_price.getText().toString().substring(1, finish_price.getText().toString().length()));
        map.put("coefficient", radiosNum + "");
        showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.i("----" + key, "" + value + "\n");
            }
        }

        XUtil.Post(Url.BATH_MAKEBUDGETORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Intent intent = new Intent(ReservedDetailActivity.this, ProjectOrderActivity.class);
                        Gson g = new Gson();
                        YusuanOrderBean bean = g.fromJson(result, YusuanOrderBean.class);
                        intent.putExtra("bean", bean);
                        intent.putExtra("allMoney", finish_price.getText().toString().substring(1, finish_price.getText().toString().length()));
                        intent.putExtra("statu", 123);
                        startActivity(intent);
//                        MyApplication.getInstance().destoryActivity("yusaundan");
                        EventBus.getDefault().post(new Finish1());
                        finish();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });

    }

    private void initCustomOptionPicker() {//条件选择器初始化，自定义布局
        final List<String> radios = new ArrayList<>();
        radios.clear();
        final DecimalFormat df = new DecimalFormat("######0.0");
        for (int i = 0; i < radioBean.getInfo().getCoefficient_list().size(); i++) {
            radios.add(radioBean.getInfo().getCoefficient_list().get(i).getConf());
        }

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                radiosNum = Double.parseDouble(radios.get(options1));
                radio.setText(radios.get(options1));
                finish_price.setText("￥" + df.format(Double.parseDouble(init_price.getText().toString().substring(1, init_price.getText().toString().length())) * Double.parseDouble(radios.get(options1))));
                updatePrice();
                base.notifyDataSetChanged();
            }
        }).setTitleSize(16)//标题文字大小
                .setTitleText("预算系数")
                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色
                .build();
        pvOptions.setPicker(radios);
        pvOptions.show();
    }

    private double radiosNum = 1;
}
